<template>
  <div class="feedback-container">
    <div class="feedback-content">
      <!-- 左侧反馈表单 -->
      <div class="feedback-form">
        <h2>意见反馈</h2>
        <p class="subtitle">您的建议是我们进步的动力</p>

        <a-form :form="form" @submit="handleSubmit">
          <!-- 反馈类型 -->
          <a-form-item label="反馈类型">
            <a-radio-group v-decorator="[
              'type',
              { rules: [{ required: true, message: '请选择反馈类型' }] }
            ]">
              <a-radio value="1">问题反馈</a-radio>
              <a-radio value="2">功能建议</a-radio>
              <a-radio value="3">体验优化</a-radio>
            </a-radio-group>
          </a-form-item>

          <!-- 反馈标题 -->
          <a-form-item label="标题">
            <a-input
              v-decorator="[
                'title',
                { rules: [{ required: true, message: '请输入反馈标题' }] }
              ]"
              placeholder="请简要描述您的反馈"
            />
          </a-form-item>

          <!-- 反馈内容 -->
          <a-form-item label="详细描述">
            <a-textarea
              v-decorator="[
                'content',
                { rules: [{ required: true, message: '请输入反馈内容' }] }
              ]"
              :rows="6"
              placeholder="请详细描述您遇到的问题或建议..."
            />
          </a-form-item>

          <!-- 联系方式 -->
          <a-form-item label="联系方式">
            <a-input
              v-decorator="[
                'contact',
                { rules: [{ required: true, message: '请留下您的联系方式' }] }
              ]"
              placeholder="请留下您的邮箱或手机号，方便我们及时回复"
            />
          </a-form-item>

          <!-- 图片上传 -->
          <a-form-item label="上传截图（选填）">
            <a-upload
              list-type="picture-card"
              :file-list="fileList"
              :customRequest="handleUpload"
              :beforeUpload="beforeUpload"
              @preview="handlePreview"
              @change="handleChange"
              @remove="handleRemove"
            >
              <div v-if="fileList.length < 3">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
          </a-form-item>

          <!-- 提交按钮 -->
          <a-form-item>
            <div class="form-buttons">
              <a-button type="primary" html-type="submit" :loading="submitting">
                提交反馈
              </a-button>
              <a-button @click="$router.push('/')">返回首页</a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>

      <!-- 右侧说明 -->
      <div class="feedback-info">
        <div class="info-card">
          <h3>反馈须知</h3>
          <ul>
            <li>
              <a-icon type="check-circle" theme="filled" />
              <span>请详细描述您遇到的问题或建议</span>
            </li>
            <li>
              <a-icon type="check-circle" theme="filled" />
              <span>可以上传截图以便我们更好地理解问题</span>
            </li>
            <li>
              <a-icon type="check-circle" theme="filled" />
              <span>我们会在2个工作日内回复您的反馈</span>
            </li>
            <li>
              <a-icon type="check-circle" theme="filled" />
              <span>您的反馈将帮助我们提供更好的服务</span>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="preview" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import request from '@/utils/request'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  name: 'Feedback',
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: '',
      submitting: false,
      uploadedImages: [] // 存储上传成功的图片URL
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this)
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.submitting = true
          try {
            // 构建请求参数
            const params = {
              type: values.type,
              title: values.title,
              description: values.content,
              contact: values.contact,
              images: this.uploadedImages.join(',')
            }

            // 调用反馈API
            const res = await request.post('/auth/feedback/submit', params)
            
            if (res.code === 200) {
              this.$message.success('反馈提交成功！')
              this.$router.push('/')
            } else {
              this.$message.error(res.msg || '提交失败')
            }
          } catch (error) {
            console.error('提交反馈失败:', error)
            this.$message.error('提交失败，请稍后重试')
          } finally {
            this.submitting = false
          }
        }
      })
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 文件上传前校验
    beforeUpload(file) {
      // 检查文件类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件！')
        return false
      }
      
      // 检查文件大小（限制为2MB）
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB！')
        return false
      }
      
      return true
    },
    // 自定义上传方法
    async handleUpload({ file, onSuccess, onError }) {
      try {
        const formData = new FormData()
        formData.append('file', file)

        // 调用上传接口
        const res = await request.post('/oss/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.code === 200) {
          // 保存上传成功的图片URL
          this.uploadedImages.push(res.content)
          onSuccess(res.content)
          this.$message.success('图片上传成功')
        } else {
          onError(new Error(res.msg || '上传失败'))
          this.$message.error(res.msg || '图片上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        onError(error)
        this.$message.error('图片上传失败')
      }
    },
    // 处理图片删除
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      if (index !== -1) {
        // 从uploadedImages中移除对应的URL
        this.uploadedImages.splice(index, 1)
      }
    }
  }
}
</script>

<style scoped>
.feedback-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.feedback-content {
  display: flex;
  gap: 40px;
}

.feedback-form {
  flex: 1;
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.feedback-form h2 {
  font-size: 24px;
  color: #1f2937;
  margin-bottom: 8px;
}

.subtitle {
  color: #6b7280;
  margin-bottom: 32px;
}

.form-buttons {
  display: flex;
  gap: 16px;
}

.feedback-info {
  width: 320px;
}

.info-card {
  background: #f8fafc;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.info-card h3 {
  font-size: 18px;
  color: #1f2937;
  margin-bottom: 20px;
}

.info-card ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-card li {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
  color: #4b5563;
  line-height: 1.5;
}

.info-card li:last-child {
  margin-bottom: 0;
}

.info-card :deep(.anticon) {
  color: #10b981;
  font-size: 16px;
  margin-top: 2px;
}

/* 上传组件样式 */
:deep(.ant-upload-select-picture-card) {
  width: 100px;
  height: 100px;
  margin: 0 8px 8px 0;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
  color: #374151;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .feedback-content {
    flex-direction: column;
  }

  .feedback-info {
    width: 100%;
  }
}
</style> 